//
//  FilterViewController.m
//  Finance
//
//  Created by cheng xiang on 13-8-1.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "FilterViewController.h"

#import "WEPopoverContentViewController.h"
#import "FilterResultViewController.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
@interface FilterViewController ()

@end

@implementation FilterViewController

@synthesize aTableView = _aTableView,bankDic = _bankDic, conditionDic = _conditionDic;
@synthesize popController = _popController,sender = _sender,editField = _editField,resignBtn = _resignBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark -
#pragma mark WEPopoverControllerDelegate implementation

- (void)popoverControllerDidDismissPopover:(WEPopoverController *)thePopoverController {
	//Safe to release the popover here
	self.popController = nil;
}

- (BOOL)popoverControllerShouldDismissPopover:(WEPopoverController *)thePopoverController {
	//The popover is automatically dismissed if you click outside it, unless you return NO here
	return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(goReturn)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    _bankDic = [[NSMutableDictionary alloc] init];
    
    _conditionDic = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"不限",@"不限",@"0",@"人民币",@"在售", nil] forKeys:[NSArray arrayWithObjects:@"预期收益率",@"产品类型",@"认购起点",@"货币类型",@"起售时间", nil]];
    
    _aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-88) style:UITableViewStyleGrouped];
    _aTableView.dataSource = self;
    _aTableView.delegate = self;
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:_aTableView.bounds];
    backgroundView.image = [UIImage imageNamed:@"beij.png"];
    [_aTableView setBackgroundView:backgroundView];
    [_aTableView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_aTableView];
    

    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIButton *resultBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    resultBtn.frame = CGRectMake(0, 7, 105, 30);
    [resultBtn addTarget:self action:@selector(goResult) forControlEvents:UIControlEventTouchUpInside];
    [resultBtn setBackgroundImage:[UIImage imageNamed:@"result.png"] forState:UIControlStateNormal];
    [resultBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:resultBtn];
    [self setToolbarItems:[NSArray arrayWithObjects:spaceItem,item,spaceItem, nil]animated:YES];
//    UIImage *root_image = [UIImage imageNamed:@"toolbar.jpg"];
//    if ([self.navigationController.toolbar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)]) {
//        [self.navigationController.toolbar setBackgroundImage:root_image forToolbarPosition:0 barMetrics:0];         //仅5.0以上版本适用
//    }else{
//        self.navigationController.toolbar.barStyle = UIToolbarPositionTop;
//    }
    [self.navigationController.toolbar setBarStyle:UIToolbarPositionTop];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectBenifit:) name:@"CLICKONBENIFT" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textfieldEditing:) name:@"TEXTFIELDEDITING" object:nil];
    
    [self packageRequest];
}

- (void)packageRequest
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W119"];
 
    NSDictionary *body = [[NSDictionary alloc] init];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    //发送报文
    [self getTableData: requestJson];
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryBanks"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)requestCallBack:(NSDictionary *)dic
{
    NSObject *body = dic[@"body"];
    NSLog(@"%@",[body class]);
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"banks"] != nil)
    {
        NSArray *bankArray = [(NSDictionary *)body objectForKey:@"banks"];
        for (NSDictionary *dic in bankArray) {
            [_bankDic setObject:@"1" forKey:dic];
        }
    }
    [_aTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    self.navigationController.toolbarHidden = NO;
    [super viewDidAppear:animated];
}

- (void)selectBenifit:(NSNotification *)notification
{
    NSString *title = [notification object];
    UIButton *btn = (UIButton *)_sender;
    [btn setTitle:title forState:UIControlStateNormal];
    [_conditionDic setObject:title forKey:@"预期收益率"];
    [self.popController dismissPopoverAnimated:YES];
    self.popController = nil;
}

- (void)textEditDone:(NSString *)text forKey:(NSString *)key
{
    [_conditionDic setObject:text forKey:key];
}

- (void)textfieldEditing: (NSNotification *)notification
{
    self.editField = (UITextField *)[notification object];
    if (!_resignBtn) {
        _resignBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resignBtn addTarget:self action:@selector(clickOnResign) forControlEvents:UIControlEventTouchUpInside];
        _resignBtn.frame = [UIScreen mainScreen].bounds;
        [self.view addSubview:_resignBtn];
    }
    [self.view bringSubviewToFront:_resignBtn];
}

- (void)clickOnResign
{
    [self.editField resignFirstResponder];
    [self.view sendSubviewToBack:_resignBtn];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CLICKONBENIFT" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TEXTFIELDEDITING" object:nil];
}
- (void)goResult
{
    NSString *bank = @"";
    for (NSDictionary *key in _bankDic.allKeys) {
        NSString *value = [_bankDic objectForKey:key];
        if ([value isEqualToString:@"1"]) {
            if ([bank isEqualToString:@""]) {
                bank = [bank stringByAppendingFormat:@"%@",[key objectForKey:@"bankName"]];
            }else{
                bank = [bank stringByAppendingFormat:@",%@",[key objectForKey:@"bankName"]];
            }
        }
    }
    if (![bank isEqualToString:@""]) {
        [_conditionDic setObject:bank forKey:@"bankName"];
    }
    self.navigationController.toolbarHidden = YES;
    [self setHidesBottomBarWhenPushed:YES];
    FilterResultViewController *aController = [[FilterResultViewController alloc] init];
    aController.conditionDic = self.conditionDic;
    [self.navigationController pushViewController:aController animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return [_conditionDic.allKeys count];
    }else{
        return [_bankDic.allKeys count] + 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        return 30;
    }else{
        if (indexPath.section == 0 && [[_conditionDic allKeys] count] > indexPath.row) {
            NSString *title = [[_conditionDic allKeys] objectAtIndex:indexPath.row];
            if ([title isEqualToString:@"产品类型"]) {
                return 88;
            }
        }
        
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [_bankDic.allKeys objectAtIndex:indexPath.row-1];
    if (indexPath.section == 1 && indexPath.row != 0) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            
            [_bankDic setObject:@"0" forKey:dic];
        }else{
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [_bankDic setObject:@"1" forKey:dic];
        }
    }
}

- (void)clickOnBenifit:(id)sender
{
    _sender = sender;
    if (!self.popController) {
		
		WEPopoverContentViewController *contentViewController = [[WEPopoverContentViewController alloc] initWithStyle:UITableViewStylePlain withArray:[NSArray arrayWithObjects:@"不限",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
		self.popController = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
		self.popController.delegate = self;
        //添加不响应dismiss操作的views
		//self.popController.passthroughViews = [NSArray arrayWithObject:self.toolBar];
		
		[self.popController presentPopoverFromRect:((UIButton *)sender).frame
												inView:self.view
							  permittedArrowDirections:
         (UIPopoverArrowDirectionUp)
											  animated:YES];
        
	} else {
		[self.popController dismissPopoverAnimated:YES];
		self.popController = nil;
	}
}

- (void)FilterSelectAll
{
    for (id<NSCopying> key in _bankDic.allKeys) {
        [_bankDic setObject:@"1" forKey:key];
    }
    [_aTableView reloadData];
}

- (void)FilterSelectNone
{
    for (id<NSCopying> key in _bankDic.allKeys) {
        [_bankDic setObject:@"0" forKey:key];
    }
    [_aTableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int section = indexPath.section;
    NSString *identifier = [NSString stringWithFormat:@"cell%d at %d",indexPath.row,indexPath.section];
    if(section == 0){
        NSString *title = [[_conditionDic allKeys] objectAtIndex:indexPath.row];
        if ([title isEqualToString:@"预期收益率"]) {
            BenifitFilterCell *cell = (BenifitFilterCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[BenifitFilterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.delegate = self;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.title = title;
            }
            
            return cell;
        }else if ([title isEqualToString:@"认购起点"]){
            StartMoneyFilterCell *cell = (StartMoneyFilterCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[StartMoneyFilterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.delegate = self;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.text = title;
            }
            
            cell.textLabel.font = [UIFont systemFontOfSize:13];
            return cell;
        }else{
            FilterViewCell *cell = (FilterViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[FilterViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.delegate = self;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.title = title;
                cell.textLabel.text = title;
                cell.textLabel.font = [UIFont systemFontOfSize:13];
                if ([title isEqualToString:@"货币类型"]) {
                    [cell drawCell:[NSArray arrayWithObjects:@"人民币",@"外币", nil] withLimit:NO];
                }else if([title isEqualToString:@"产品类型"]){
                    [cell drawCell:[NSArray arrayWithObjects:@"保本",@"非保本", nil] withLimit:YES];
                }else if([title isEqualToString:@"起售时间"]){
                    [cell drawCell:[NSArray arrayWithObjects:@"在售",@"将售", nil] withLimit:NO];
                }
            }
            return cell;
        }
    }else{
        if (indexPath.row == 0) {
            FilterHeaderView *cell = (FilterHeaderView *)[tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[FilterHeaderView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.delegate = self;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.imageView.frame = CGRectMake(5, 5, 25, 25);
            }
            NSDictionary *dic = [_bankDic.allKeys objectAtIndex:indexPath.row-1];
            cell.textLabel.text = [dic objectForKey:@"bankName"];
            cell.textLabel.font = [UIFont systemFontOfSize:13];
            NSString *value = [_bankDic objectForKey:dic];
            [NSThread detachNewThreadSelector:@selector(drawBankImage:) toTarget:cell withObject:[dic objectForKey:@"bankLogo"]];
            if ([value isEqualToString:@"1"]) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }else{
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            return cell;
        }
    }
}

- (void)goReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
